package top.tanglizhi.springboot3.service.impl;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.tanglizhi.springboot3.base.R;
import top.tanglizhi.springboot3.entity.TbFiles;
import top.tanglizhi.springboot3.entity.user.AuthInfo;
import top.tanglizhi.springboot3.exception.AppException;
import top.tanglizhi.springboot3.interceptor.AppInterceptor;
import top.tanglizhi.springboot3.mapper.TbFillesMapper;
import top.tanglizhi.springboot3.service.FileService;

import java.io.*;

@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
    private final TbFillesMapper tbFillesMapper;

    @Override
    public R<TbFiles> upload(MultipartFile file) {
        if (file == null){
            return R.fail("文件为空", null);
        }
        // 保存文件信息到数据库
        TbFiles files = new TbFiles();
        files.setFileName(file.getOriginalFilename());
        files.setFileSize(file.getSize());
        files.setContentType(file.getContentType());
        AuthInfo authInfo = AppInterceptor.getAuthInfo();
        files.setUserId(authInfo.getId());

        int i = tbFillesMapper.insert(files);
        if ( i != 1) {
            return R.fail("无法保存数据库，文件上传失败", null);
        }
        // 保存文件到本地
        File dir = new File(UPLOAD_URL);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = String.format("%d_%s", files.getId(),files.getFileName());
        try {
            InputStream is = file.getInputStream();
            OutputStream os = new FileOutputStream(new File(dir,fileName));
            byte[] buffer = new byte[8 * 1024];
            int len = is.read(buffer);
            while (len != -1) {
                os.write(buffer, 0, len);
                len = is.read(buffer);
                os.flush();
            }
            os.close();
            is.close();
            return R.ok("文件上传成功", files);
        } catch (Exception e) {
            throw AppException.getInstance(e.getMessage());
        }

    }

    @Override
    public void download(Integer id, HttpServletResponse response) {
        TbFiles files = tbFillesMapper.selectById(id);
        if (files == null) {
            throw AppException.getInstance("文件信息不存在");
        }
        File dir = new File(UPLOAD_URL);
        String fileName = String.format("%d_%s", files.getId(),files.getFileName());
        File file = new File(dir, fileName);
        if (!file.exists()) {
            throw AppException.getInstance("文件不存在");
        }
        try {
            byte[] nbuffer = files.getFileName().getBytes("UTF-8");
            String urlname = new String(nbuffer, "ISO-8859-1");
            response.reset();
            response.setContentType(files.getContentType());
            response.setHeader("Content-Disposition", "attachment;filename=" + urlname);
            response.setContentLengthLong(files.getFileSize());
            InputStream is = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[8 * 1024];
            int len = is.read(buffer);
            while (len != -1) {
                os.write(buffer, 0, len);
                len = is.read(buffer);
                os.flush();
            }
            os.close();
            is.close();
        } catch (Exception ex) {
            throw AppException.getInstance(ex.getMessage());
        }

    }

}
